const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
const formatDateTime = require('../utils/formatDateTime');



// 获取教师的批改任务分页数据
exports.getReviewAssignmentOfPerson = async (req, res) => {
  try {
    const { id, page = 1, pageSize = 10, timeOrder = 'desc', status } = req.query;
    
    // 验证参数
    if (!id) {
      return res.status(400).json({
        code: 400,
        message: '用户ID不能为空',
        success: false
      });
    }

    // 转换为数字类型
    const userId = parseInt(id);
    const currentPage = parseInt(page);
    const limit = parseInt(pageSize);
    const offset = (currentPage - 1) * limit;
    
    // 构建查询条件
    let whereCondition = {
      user_id: userId
    };
    
    // 如果传递了状态参数且不为"所有状态"，添加到查询条件中
    if (status && status !== '所有状态') {
      whereCondition.status = parseInt(status);
    }
    
    // 查询总数
    const total = await prisma.review_assignment.count({
      where: whereCondition
    });
    
    // 获取批阅任务列表
    let assignments = await prisma.review_assignment.findMany({
      where: whereCondition,
      orderBy: {
        start_time: timeOrder === 'desc' ? 'desc' : 'asc'
      },
      skip: offset,
      take: limit,
      select: {
        id: true,
        examination_id: true,
        assignment_strategy: true,
        start_time: true,
        end_time: true,
        status: true
      }
    });
    
    // 获取考试信息和批阅详情信息
    const assignmentList = await Promise.all(assignments.map(async (assignment) => {
      // 获取考试名称
      const examination = await prisma.examination.findUnique({
        where: { id: assignment.examination_id },
        select: { name: true }
      });
      
      let detailCount = 0;
      let doneCount = 0;
      
      // 根据分配策略采用不同的统计方式
      if (assignment.assignment_strategy === 1) {
        // 策略1: 按试卷分配 - 查询该任务下有多少张不同学生的试卷
        
        // 先获取该批阅任务下所有的review_assignment_detail记录
        const assignmentDetails = await prisma.review_assignment_detail.findMany({
          where: { 
            review_assignment_id: assignment.id,
            student_paper_id: { not: null } // 确保是按试卷分配的
          },
          select: {
            student_paper_id: true,
            status: true
          }
        });
        
        // 用Set去重，计算有多少不同的student_paper_id
        const uniquePaperIds = new Set(assignmentDetails.map(detail => detail.student_paper_id));
        detailCount = uniquePaperIds.size; // 总共分配的不同学生试卷数量
        
        // 直接从student_paper表中查询examination_status=2（批阅完成）的记录数量
        doneCount = await prisma.student_paper.count({
          where: {
            id: { in: [...uniquePaperIds] },
            examination_status: 2  // 2表示批阅完成
          }
        });
        
      } else if (assignment.assignment_strategy === 2) {
        // 策略2: 按题目分配 - 查询该任务涉及的题目详情总数和已完成数量
        detailCount = await prisma.review_assignment_detail.count({
          where: { 
            review_assignment_id: assignment.id,
            paper_detail_id: { not: null } // 确保是按题目分配的
          }
        });
        
        doneCount = await prisma.review_assignment_detail.count({
          where: { 
            review_assignment_id: assignment.id,
            paper_detail_id: { not: null },
            status: 1 
          }
        });
      } 
      
      return {
        id: assignment.id,
        examinationName: examination?.name || '',
        assignmentStrategy: assignment.assignment_strategy,
        startTime: formatDateTime(assignment.start_time),
        endTime: formatDateTime(assignment.end_time),
        status: assignment.status,
        detailCount,
        doneCount
      };
    }));
    
    return res.status(200).json({
      code: 200,
      message: '获取批阅任务成功',
      success: true,
      data: {
        list: assignmentList,
        total
      }
    });
    
  } catch (error) {
    console.error('获取批阅任务失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取批阅任务失败',
      success: false,
      error: error.message
    });
  }
};

// 获取批阅任务的试卷详情数据（按整张试卷来查询）
exports.getTaskDetailByOne = async (req, res) => {
  try {
    const { reviewAssignmentId, page = 1, pageSize = 10, status } = req.query;
    
    // 参数验证
    if (!reviewAssignmentId) {
      return res.status(400).json({
        code: 400,
        message: '批阅任务ID不能为空',
        success: false
      });
    }

    // 参数转换
    const assignmentId = parseInt(reviewAssignmentId);
    const currentPage = parseInt(page);
    const limit = parseInt(pageSize);
    const offset = (currentPage - 1) * limit;

    // 首先检查批阅任务是否存在
    const reviewAssignment = await prisma.review_assignment.findUnique({
      where: { id: assignmentId }
    });

    if (!reviewAssignment) {
      return res.status(404).json({
        code: 404,
        message: '批阅任务不存在',
        success: false
      });
    }

    // 获取该批阅任务关联的所有学生试卷ID（去重）
    const paperDetails = await prisma.review_assignment_detail.findMany({
      where: { 
        review_assignment_id: assignmentId,
        student_paper_id: { not: null } // 确保是按试卷分配的
      },
      select: {
        student_paper_id: true,
        status: true
      }
    });

    // 获取不重复的学生试卷ID
    const uniquePaperIds = [...new Set(paperDetails.map(detail => detail.student_paper_id))];

    // 获取student_paper表中的examination_status信息
    const studentPapersWithStatus = await prisma.student_paper.findMany({
      where: {
        id: {
          in: uniquePaperIds
        }
      },
      select: {
        id: true,
        examination_status: true
      }
    });

    // 创建一个映射表，用于存储每个student_paper_id对应的examination_status
    const statusMap = new Map();
    studentPapersWithStatus.forEach(paper => {
      statusMap.set(paper.id, paper.examination_status || 0);
    });

    // 根据examination_status字段排序uniquePaperIds
    uniquePaperIds.sort((a, b) => {
      const statusA = statusMap.get(a) || 0;
      const statusB = statusMap.get(b) || 0;
      return statusA - statusB;
    });

    // 计算总试卷数
    const total = uniquePaperIds.length;
    
    // 查询已完成批阅的试卷数量
    let doneTotal = 0;
    if (reviewAssignment.assignment_strategy === 1) {
      // 直接从student_paper表中查询examination_status=2（批阅完成）的记录数量
      doneTotal = await prisma.student_paper.count({
        where: {
          id: { in: uniquePaperIds },
          examination_status: 2  // 2表示批阅完成
        }
      });
    } else {
      for (const paperId of uniquePaperIds) {
        // 获取该试卷所有批阅详情
        const paperDetailStatuses = await prisma.review_assignment_detail.findMany({
          where: {
            review_assignment_id: assignmentId,
            student_paper_id: paperId
          },
          select: {
            status: true
          }
        });
        
        // 如果该试卷的所有批阅详情都已完成（status=1），则计入已完成数量
        if (paperDetailStatuses.length > 0 && paperDetailStatuses.every(detail => detail.status === 1)) {
          doneTotal++;
        }
      }
    }

    // 构建查询条件，根据状态过滤学生试卷
    let filteredPaperIds = [...uniquePaperIds];
    
    // 如果指定了状态筛选，则只保留符合条件的试卷ID
    if (status && status !== '所有状态') {
      const statusFilter = parseInt(status);
      
      // 过滤出对应状态的试卷ID
      filteredPaperIds = [];
      for (const paperId of uniquePaperIds) {
        const paperDetailStatuses = await prisma.review_assignment_detail.findMany({
          where: {
            review_assignment_id: assignmentId,
            student_paper_id: paperId
          },
          select: {
            status: true
          }
        });
        
        // 判断试卷的状态
        const allComplete = paperDetailStatuses.length > 0 && paperDetailStatuses.every(detail => detail.status === 1);
        
        // 状态1表示已完成批阅，0表示未完成批阅
        if ((statusFilter === 1 && allComplete) || (statusFilter === 0 && !allComplete)) {
          filteredPaperIds.push(paperId);
        }
      }
    }

    // 进行分页
    const paginatedPaperIds = filteredPaperIds.slice(offset, offset + limit);


    // 获取每张试卷的详细信息
    const list = await Promise.all(paginatedPaperIds.map(async (paperId) => {
      // 获取学生试卷信息
      const studentPaper = await prisma.student_paper.findUnique({
        where: { id: paperId }
      });

      if (!studentPaper) return null;

      // 获取学生信息
      const student = await prisma.user.findUnique({
        where: { id: studentPaper.user_id }
      });

      // 获取学生班级信息
      const studentClass = await prisma.student_classes.findFirst({
        where: { student_id: studentPaper.user_id }
      });

      let classesName = '';
      if (studentClass) {
        const classes = await prisma.classes.findUnique({
          where: { id: studentClass.classes_id }
        });
        classesName = classes ? classes.name : '';
      }

      // 获取该试卷在review_assignment_detail表中的所有记录数量
      const totalCount = await prisma.review_assignment_detail.count({
        where: { 
          review_assignment_id: assignmentId,
          student_paper_id: paperId 
        }
      });

      // 获取该试卷在review_assignment_detail表中已批阅完成的记录数量(status=1)
      const doneCount = await prisma.review_assignment_detail.count({
        where: { 
          review_assignment_id: assignmentId,
          student_paper_id: paperId,
          status: 1
        }
      });

      // 判断该试卷是否已经全部批阅完成
      const status = totalCount > 0 && doneCount === totalCount ? 1 : 0;

      return {
        id: paperId,
        studentName: student ? student.name : '',
        account: student ? student.account : '',
        classesName,
        doneCount,
        detailCount: totalCount,  
        status
      };
    }));

    // 过滤掉null值
    const validList = list.filter(item => item !== null);

    return res.status(200).json({
      code: 200,
      message: 'success',
      success: true,
      data: {
        list: validList,
        total,
        doneTotal,
        uniquePaperIds
      }
    });
    
  } catch (error) {
    console.error('获取批阅详情失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取批阅详情失败',
      success: false,
      error: error.message
    });
  }
};

// 获取批阅任务的主观题详情数据（按单道大题来查询）
exports.getTaskDetailByTwo = async (req, res) => {
  try {
    const { reviewAssignmentId, page = 1, pageSize = 10, status } = req.query;
    console.log(reviewAssignmentId, page, pageSize, status);
    
    // 参数验证
    if (!reviewAssignmentId) {
      return res.status(400).json({
        code: 400,
        message: '批阅任务ID不能为空',
        success: false
      });
    }

    // 参数转换
    const assignmentId = parseInt(reviewAssignmentId);
    const currentPage = parseInt(page);
    const limit = parseInt(pageSize);
    const offset = (currentPage - 1) * limit;

    // 首先检查批阅任务是否存在
    const reviewAssignment = await prisma.review_assignment.findUnique({
      where: { id: assignmentId }
    });



    if (!reviewAssignment) {
      return res.status(404).json({
        code: 404,
        message: '批阅任务不存在',
        success: false
      });
    }

    // 确认是按单道大题分配的批阅任务
    if (reviewAssignment.assignment_strategy !== 2) {
      return res.status(400).json({
        code: 400,
        message: '该批阅任务不是按单道大题分配的',
        success: false
      });
    }

    // 获取该批阅任务关联的所有主观题批阅详情
    const paperDetailsQuery = {
      where: { 
        review_assignment_id: assignmentId,
        paper_detail_id: { not: null } // 确保是按题目分配的
      }
    };

    // 获取符合条件的总记录数
    const total = await prisma.review_assignment_detail.count({
      where: paperDetailsQuery.where
    });
    
    // 获取已完成批阅的题目数量
    const doneTotal = await prisma.review_assignment_detail.count({
      where: { 
        review_assignment_id: assignmentId,
        paper_detail_id: { not: null },
        status: 1
      }
    });

    // 如果指定了状态筛选，添加状态条件
    if (status && status !== '所有状态') {
      paperDetailsQuery.where.status = parseInt(status);
    }

    // 添加select信息用于获取详情
    paperDetailsQuery.select = {
      id: true,
      paper_detail_id: true,
      status: true
    };

    // 分页查询
    paperDetailsQuery.skip = offset;
    paperDetailsQuery.take = limit;

    // 获取分页数据
    const assignmentDetails = await prisma.review_assignment_detail.findMany(paperDetailsQuery);

    // 获取该批阅任务下的所有批阅详情id
    const reviewAssignmentDetailIds = await prisma.review_assignment_detail.findMany({
      where: { 
        review_assignment_id: assignmentId,
        paper_detail_id: { not: null }
      },
      select: {
        id: true
      }
    }).then(results => results.map(detail => detail.id));

    // 获取每道题的详细信息
    const list = await Promise.all(assignmentDetails.map(async (detail) => {
      // 获取试卷详情信息
      const paperDetail = detail.paper_detail_id ? await prisma.paper_detail.findUnique({
        where: { id: detail.paper_detail_id }
      }) : null;

      if (!paperDetail) return null;

      // 获取学生试卷信息
      const studentPaper = await prisma.student_paper.findUnique({
        where: { id: paperDetail.student_paper_id }
      });

      if (!studentPaper) return null;

      // 获取学生信息
      const student = await prisma.user.findUnique({
        where: { id: studentPaper.user_id }
      });

      // 获取学生班级信息
      const studentClass = await prisma.student_classes.findFirst({
        where: { student_id: studentPaper.user_id }
      });

      let classesName = '';
      if (studentClass) {
        const classes = await prisma.classes.findUnique({
          where: { id: studentClass.classes_id }
        });
        classesName = classes ? classes.name : '';
      }

      // 获取题目信息
      const question = await prisma.question.findUnique({
        where: { id: paperDetail.question_id }
      });

      return {
        id: detail.id,
        studentName: student ? student.name : '',
        account: student ? student.account : '',
        classesName,
        questionName: question ? question.name : '',
        status: detail.status
      };
    }));

    // 过滤掉null值
    const validList = list.filter(item => item !== null);
    
    return res.status(200).json({
      code: 200,
      message: 'success',
      data: {
        list: validList,
        total,
        doneTotal,
        reviewAssignmentDetailIds
      }
    });
    
  } catch (error) {
    console.error('获取批阅详情失败:', error);
    return res.status(500).json({
      code: 500,
      message: '获取批阅详情失败',
      success: false,
      error: error.message
    });
  }
};
